import java.util.PriorityQueue;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: Administrator
 * \* Date: 2022/4/1
 * \* Time: 15:47
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 */

//创建一个类，表示一个任务
class Mytask implements Comparable<Mytask>{
    //任务具体是什么
    private Runnable runnable;
    //任务具体实施的时间，保存任务要执行的毫秒级时间戳
    private long time;
    //delay，不是绝对的时间戳的值
    public Mytask(Runnable runnable, long delay) {
        this.runnable = runnable;
        //进行换算
        this.time = System.currentTimeMillis() + delay;
    }
    public void run(){
        runnable.run();
    }
    public long getTime() {
        return time;
    }
    @Override
    public int compareTo(Mytask o) {
        return (int) (this.time - o.time);
    }
}



class MyTimer{
    //定时器内部要能够存放多个任务
    PriorityBlockingQueue<Mytask> queue = new PriorityBlockingQueue<>();

    public void schedule(Runnable runnable,long delay){
        Mytask task = new Mytask(runnable,delay);
        //每次插入任务之后，都唤醒一下并且扫描线程，
        //让线程重新检查一下队首的任务是否到时间执行了
        synchronized (locker){
            locker.notify();
        }
        queue.put(task);
    }

    private Object locker = new Object();
    public MyTimer(){
        Thread t = new Thread(()->{
            try {
                //先取出队首元素
                Mytask task = queue.take();
                //再比较一下当前这个任务时间到了没
                long curTime = System.currentTimeMillis();
                if(curTime < task.getTime()){
                    //如果时间没到，把任务塞回队列中，
                    queue.put(task);
                    //指定一个等待时间，
                    synchronized (locker){
                        locker.wait(task.getTime() - curTime);
                    }
                }else{
                    //时间到了，执行这个任务
                    task.run();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t.start();
    }
}


public class Demo24 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello world");
            }
        },3000);
        System.out.println("main");
    }
}
